package com.example.myapplication;
import android.Manifest;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private AppCompatTextView startTextView;
    private AppCompatTextView notificationTextView;
    private AppCompatTextView progressTextView;
    private AppCompatTextView modifyTextView;

    private NotificationCompat.Builder builder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startTextView = findViewById(R.id.startTextView);
        notificationTextView = findViewById(R.id.notificationTextView);
        progressTextView = findViewById(R.id.progressTextView);
        modifyTextView = findViewById(R.id.modifyTextView);

        //取到系统通知管理器
        NotificationManager notificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
        //如果是android 8.0 以上 需要自行配置通知渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //新建一个通知渠道
            NotificationChannel channel = new NotificationChannel("channelId", "channelId", NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        modifyTextView.setOnClickListener(view -> {
            int max = 100;
            int current = 50;
            builder.setContentText("下载中" + current + "%");
            builder.setProgress(max, current, false);
            notificationManager.notify(1, builder.build());
        });

        progressTextView.setOnClickListener(view -> {
            int max = 100;
            int current = 30;
            builder = new NotificationCompat.Builder(this, "channelId")
                    .setContentTitle("重要通知")
                    .setContentText("下载中" + current + "%")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setProgress(max, current, false)
                    .setAutoCancel(false);
            notificationManager.notify(1, builder.build());
        });

        notificationTextView.setOnClickListener(view -> {
            Intent intent = new Intent(this, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
            builder = new NotificationCompat.Builder(this, "channelId")
                    .setContentTitle("重要通知")
                    .setContentText("重要通知内容")
                    .setContentIntent(pendingIntent)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setNumber(999) // 自定义桌面通知数量
                    .addAction(R.mipmap.ic_launcher, "去看看", pendingIntent)
                    .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                    .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
                    .setAutoCancel(false);
            notificationManager.notify(1, builder.build());
        });

        startTextView.setOnClickListener(view -> {
            Intent intent = new Intent();
            intent.setPackage(getPackageName());
            intent.setAction("wulianwang");
            intent.putExtra("info", "您好");
            sendBroadcast(intent);
        });

        BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent == null) return;
                String action = intent.getAction();
                if (action == null || action.isEmpty()) return;
                if (action.equals(Intent.ACTION_TIME_TICK)) {
                    //系统每1分钟发送一次广播
                    Log.d("TAGS", "时间发生变化，1分钟");
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                    String sim = dateFormat.format(new Date());
                    Log.d("TAGS", sim);
                    int timeYear = Integer.parseInt(sim.substring(0, 4));
                    int timeMonth = Integer.parseInt(sim.substring(4, 6));
                    int timeDay = Integer.parseInt(sim.substring(6, 8));
                    int timeHour = Integer.parseInt(sim.substring(8, 10));
                    int timeMinute = Integer.parseInt(sim.substring(10, 12));
                    Log.d("TAGS", timeYear + "年" + timeMonth + "月" + timeDay + "日" + timeHour + "时" + timeMinute + "分");
                }
                if (action.equals(Intent.ACTION_TIME_CHANGED)) {
                    //系统手动更改时间发送广播
                    Log.d("TAGS", "时间发生变化，手动改变");
                }
                if (action.equals(Intent.ACTION_SCREEN_ON)) {
                    //系统手动更改时间发送广播
                    Log.d("TAGS", "屏幕被打开");
                }
                if (action.equals(Intent.ACTION_SCREEN_OFF)) {
                    //系统手动更改时间发送广播
                    Log.d("TAGS", "屏幕被关闭");
                }
            }
        };

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_TIME_TICK);
        filter.addAction(Intent.ACTION_TIME_CHANGED);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        registerReceiver(broadcastReceiver, filter);

    }

    @Override
    protected void onResume() {
        super.onResume();
        String[] permissionArray = new String[]{
                Manifest.permission.CAMERA,
                Manifest.permission.READ_CONTACTS,
                Manifest.permission.WRITE_CONTACTS,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
        };
        List<String> list = new ArrayList<>();
        for (String permissions : permissionArray) {
            if (ContextCompat.checkSelfPermission(this, permissions) != PackageManager.PERMISSION_GRANTED) {
                list.add(permissions);
            } else {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, permissions)) {
                    list.add(permissions);
                }
            }
        }
        if (list.size() > 0) {
            ActivityCompat.requestPermissions(this, list.toArray(new String[0]), 0);
            Toast.makeText(this, "缺少必要的权限", Toast.LENGTH_LONG).show();
            finish();
        }
    }

}
